package com.baidu.videoseries.fragment;


import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.SeekBar;

import com.baidu.videoseries.R;
import com.baidu.videoseries.constant.Config;
import com.baidu.videoseries.util.LogUtils;
import com.kvin.toolkit.utils.ThreadPoolUtils;

import org.videolan.libvlc.LibVLC;
import org.videolan.libvlc.Media;
import org.videolan.libvlc.MediaPlayer;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 */
public class VlcFragment extends BaseFragment implements SurfaceHolder.Callback{


    @BindView(R.id.video_surface)
    SurfaceView videoSurface;
    @BindView(R.id.loading_view)
    ProgressBar loadingView;
    @BindView(R.id.seek_bar)
    SeekBar seekBar;
    @BindView(R.id.play_button)
    ImageButton playButton;
    Unbinder unbinder;


    private SurfaceHolder mSurfaceHolder;

    private LibVLC mLibVLC;
    private MediaPlayer mMediaPlayer;
    private Media mMedia;

    private static final int MOVE_SPEED = 100;
    private boolean isPlaying = true;

    public VlcFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.activity_vlc, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }


    @Override
    public void init() {

        //init view
        seekBar.setOnSeekBarChangeListener(mSeekBarChangedListener);

        mSurfaceHolder = videoSurface.getHolder();
        mSurfaceHolder.addCallback(this);
        mSurfaceHolder.setFormat(PixelFormat.RGBX_8888);
        mSurfaceHolder.setKeepScreenOn(true);
        //init player here
        ArrayList<String> args = new ArrayList<>();
        args.add("-vvv");
        mLibVLC = new LibVLC(getActivity(),args);
        mMediaPlayer = new MediaPlayer(mLibVLC);
        mMediaPlayer.setEventListener(mEventListener);
        mMedia = new Media(mLibVLC, Uri.parse(Config.Urls.VIDEO_HUHU));
        ThreadPoolUtils.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    mMediaPlayer.setMedia(mMedia);
                    mMedia.parseAsync();
                    mMediaPlayer.setTitle(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });


    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        //bind surface
        mMediaPlayer.getVLCVout().setVideoView(videoSurface);
        mMediaPlayer.getVLCVout().attachViews();
        mMediaPlayer.setSpuDelay(2 * 1000);
        mMediaPlayer.play();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {

    }

    @Override
    public void onPause() {
        super.onPause();
        LogUtils.e("---------------------onPause");
        if (mMediaPlayer != null && mMediaPlayer.isPlaying()) mMediaPlayer.stop();
    }


    @Override
    public void onResume() {
        super.onResume();
        LogUtils.e("---------------------onResume");
        if (mMediaPlayer != null && !mMediaPlayer.isPlaying()) {
            mMediaPlayer.play();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mMediaPlayer != null) {
            mMediaPlayer.stop();
            mMediaPlayer.release();
            mMedia.release();
            mLibVLC.release();
        }
    }

    /**
     * event listener
     */
    private MediaPlayer.EventListener mEventListener = new MediaPlayer.EventListener() {
        @Override
        public void onEvent(MediaPlayer.Event event) {
//            LogUtils.e("--" + event.type);
            switch (event.type) {
                case MediaPlayer.Event.Opening:
                    LogUtils.e("--" + event.type + " :length=" + mMediaPlayer.getLength());
                    break;
                case MediaPlayer.Event.Playing:
                    loadingView.setVisibility(View.GONE);
                    isPlaying = true;
                    break;
                case MediaPlayer.Event.Stopped:
                    isPlaying = false;
                    break;
                case MediaPlayer.Event.TimeChanged:
                    int progress = (int) (mMediaPlayer.getTime() / 1000);
                    seekBar.setProgress(progress);
//                    LogUtils.e("time=" + mMediaPlayer.getTime());
                    break;
                case MediaPlayer.Event.Vout:
                    int length = (int) mMediaPlayer.getLength() / 1000;
                    seekBar.setMax(length);
                    if (!mMediaPlayer.isPlaying()) mMediaPlayer.play();
                    LogUtils.e("Vout", " :length=" + mMediaPlayer.getLength());
                    break;
                case MediaPlayer.Event.MediaChanged:
                    mMediaPlayer.pause();
                    break;
            }
        }
    };

    /**
     * seek bar changed listener
     */
    private SeekBar.OnSeekBarChangeListener mSeekBarChangedListener = new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser) {
                mMediaPlayer.setTime(progress * 1000);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            if (mMediaPlayer != null) mMediaPlayer.play();
        }
    };

    /**
     * gesture listener
     */
    private GestureDetector.OnGestureListener mGestureListener = new GestureDetector.OnGestureListener() {
        @Override
        public boolean onDown(MotionEvent e) {
            LogUtils.e("onDown" + "--------");
            showView();
            return true;
        }

        @Override
        public void onShowPress(MotionEvent e) {
            LogUtils.e("onShowPress" + "--------");
        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            LogUtils.e("onSingleTapUp" + "--------");
            singleTopEvent();
            return true;
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            LogUtils.e("onScroll" + "--------" + e2.getAction());
            long progress = (long) (mMediaPlayer.getTime() - distanceX * MOVE_SPEED);
            if (progress >= 0 && progress <= seekBar.getMax() * 1000) {
                mMediaPlayer.setTime(progress);
            }
            return true;
        }

        @Override
        public void onLongPress(MotionEvent e) {
            LogUtils.e("onLongPress" + "--------");

        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            LogUtils.e("onFling" + "--------");
            hideView();
            return true;
        }
    };

    private void singleTopEvent() {
        this.playButton.setVisibility(View.VISIBLE);
        if (isPlaying) {
            mMediaPlayer.pause();
            playButton.setBackgroundResource(R.mipmap.icon_pop_play);
            isPlaying = false;
        } else {
            mMediaPlayer.play();
            playButton.setBackgroundResource(R.mipmap.icon_pop_pause);
            isPlaying = true;
        }
        hideView();
    }



    /**
     * hide view
     */

    private void hideView() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                playButton.setVisibility(View.INVISIBLE);
                seekBar.setVisibility(View.INVISIBLE);
            }
        }, 5 * 1000);

    }

    /**
     * show view and change pictures
     */
    private void showView() {
        this.seekBar.setVisibility(View.VISIBLE);
    }

    /**
     * use for update view
     */
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
